package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.util.Log;

import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.database.LocalDataBase;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindGroupBean;
import com.qiantu.api.entity.KGXAddData;
import com.qiantu.api.entity.KGXcollectionData;
import com.qiantu.api.entity.ProtocolSwitchResultBean;
import com.qiantu.api.entity.UniversalDeviceAction;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.Request.KGXRequest;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AddDeviceBean;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.BottomKGXDeviceAddressDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.AddDeviceParseUtil;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomProtocolSwitchDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.io.Console;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class  KGXControllerSettingActivity extends AppActivity {
    private SettingBar itemSmartControllerName;
    private SettingBar itemSmartControllerId;
    private SettingBar itemSmartPanelConfig;
    private SettingBar itemLoadDevice;
    private TextView btnStopStartUsing;
    private View itemStopStartUsing;
    long[] mHits = new long[3];// 数组长度表示要点击的次数，3表示3次点击，4表示4次点击。数组初始化都为0
    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private KGXcollectionData deviceCollectBean;

    private List<KGXcollectionData> deviceCollects;

    private BottomKGXDeviceAddressDialog typeCountDialog;


    public static void start(Context context, KGXcollectionData deviceCollectBean, List<KGXcollectionData> deviceCollects) {
        Intent intent = new Intent(context, KGXControllerSettingActivity.class);
        intent.putExtra("deviceCollectBean", deviceCollectBean);
        intent.putExtra("deviceCollects", (Serializable) deviceCollects);

        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_controller_setting_kgx;
    }

    @Override
    protected void initView() {
        deviceCollectBean = getSerializable("deviceCollectBean");
        deviceCollects =
                (List<KGXcollectionData>) getIntent().getSerializableExtra("deviceCollects");
        itemSmartControllerName = findViewById(R.id.item_smart_controller_name);
        itemSmartControllerId = findViewById(R.id.item_smart_controller_id);
        itemSmartPanelConfig = findViewById(R.id.item_smart_panel_config);
        itemLoadDevice = findViewById(R.id.item_load_device);
        btnStopStartUsing = findViewById(R.id.btn_stop_start_using);
        itemStopStartUsing = findViewById(R.id.item_stop_start_using);
        View btnDelete = findViewById(R.id.btn_delete);
        setOnClickListener(itemSmartControllerName,itemSmartControllerId, itemLoadDevice, btnStopStartUsing, btnDelete, itemSmartPanelConfig);
    }

    @Override
    protected void initData() {
        updateView();
    }

    private void updateView(){
        setTitle("面板设置");
        btnStopStartUsing.setVisibility(View.GONE);
        itemStopStartUsing.setVisibility(View.GONE);
        itemSmartControllerId.setLeftText("485地址");
        itemSmartControllerId.setRightText(deviceCollectBean.getProtocolAddress());
        itemSmartControllerName.setRightText(deviceCollectBean.getName());
        if (deviceCollectBean.getType() == 22){//面板
            itemSmartPanelConfig.setVisibility(View.VISIBLE);//面板配置
            itemLoadDevice.setVisibility(View.GONE);
        }else{
            itemSmartPanelConfig.setVisibility(View.GONE);
            itemLoadDevice.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.item_smart_controller_name://改名字
                showBottomEditDialog(itemSmartControllerName.getRightText().toString());
                break;
            case R.id.item_smart_controller_id://改地址
                showAddressDialog();
                break;
            case R.id.item_firmware_update:
//                FirmwareUpdateActivity.start(this, controllerSerialNo, 2);
                break;
            case R.id.item_load_device:
                KGXLoadDeviceActivity.start(this, deviceCollectBean, LoadDeviceActivity.TYPE_CONTROLLER);
                break;
            case R.id.btn_delete:
                showDeleteHintDialog();
                break;
            case R.id.item_smart_panel_config:
                KGXPanelBindConfigActivity.start(getContext(), deviceCollectBean);
                break;
        }
    }



    BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setLabel(getString(R.string.kgx_controller_name));
            mBottomEditDialog.setHint(getString(R.string.kgx_controller_name_holder));
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    itemSmartControllerName.setRightText(mBottomEditDialog.getText());
                    updateControllerName(mBottomEditDialog.getText());
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.DEVICE_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void showAddressDialog() {


//        List<String> addressss = Arrays.asList(modifyProtocolAddresses(deviceCollects, deviceCollectBean));

        List<String> addressss = new ArrayList<>();
        addressss.add(deviceCollectBean.getProtocolAddress());

        if (typeCountDialog == null) {
            typeCountDialog = new BottomKGXDeviceAddressDialog(this);
            typeCountDialog.setDialogClickListener(new BottomKGXDeviceAddressDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String address) {
                    typeCountDialog.dismiss();
                    //刷新视图
                    updateAddress(address);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(typeCountDialog);
        }
        typeCountDialog.setCounts(addressss);
        typeCountDialog.setSelected(deviceCollectBean.getProtocolAddress());
        typeCountDialog.show();
    }

    // 方法：获取所有 deviceCollects 数据的 protocolAddress 字符串，修改并返回新的字符串数组
    public String[] modifyProtocolAddresses(List<KGXcollectionData> deviceCollects, KGXcollectionData deviceCollectBean) {
        // 获取所有 protocolAddresses
        List<String> protocolAddresses = new ArrayList<>();
        for (KGXcollectionData deviceCollect : deviceCollects) {
            protocolAddresses.add(deviceCollect.getProtocolAddress());
        }

        // 初始化 1-24 的字符串列表
        List<String> addressList = new ArrayList<>();
        for (int i = 1; i <= 24; i++) {
            addressList.add(String.valueOf(i));
        }

        // 移除包含在 protocolAddresses 的元素
        addressList.removeIf(address -> protocolAddresses.contains(address));

        // 获取 deviceProtocolAddress
        String deviceProtocolAddress = deviceCollectBean.getProtocolAddress();

        // 添加 deviceProtocolAddress，避免重复
        if (!addressList.contains(deviceProtocolAddress)) {
            addressList.add(deviceProtocolAddress);
        }

        // 对列表进行排序
        Collections.sort(addressList, (a, b) -> Integer.compare(Integer.parseInt(a), Integer.parseInt(b)));

        // 转换为字符串数组并返回
        return addressList.toArray(new String[0]);
    }


    private void showDeleteHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialogBuilder.setRightText(R.string.common_confirm);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                deleteController();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_controller_hint));
        mConfirmCancelHintDialog.show();
    }


    private void updateControllerName(String name){
        deviceCollectBean.setName(name);
        KGXRequest.editdevicecollectinfo(this,deviceCollectBean, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.modifying));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.reset_success);
                itemSmartControllerName.setRightText(deviceCollectBean.getName());
                updateDeviceName(name);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void updateDeviceName(String name){
        List<DeviceBean> deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerialNoAndDeviceCollectSerialNoAndBaseType(deviceCollectBean.getControllerSerialNo(),deviceCollectBean.getDeviceCollectSerialNo(),"wall_switch");
        if (!deviceBeans.isEmpty()){
            DeviceBean editDevice =  deviceBeans.get(0);
            editDevice.setName(name);
            LLHttpManager.modifyDevice(this, editDevice, new HttpCallback<HttpData<Void>>(this) {
                @Override
                public void onStart(Call call) {
                    showDialog(getString(R.string.setting));
                }

                @Override
                public void onSucceed(HttpData<Void> result) {
                    LLDeviceDBManager.getInstance(getContext()).put(editDevice);
                    toast(R.string.reset_success);
                }
                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
        }else {
            toast(R.string.reset_success);
        }
    }

    private void updateAddress(String address){
        deviceCollectBean.setProtocolAddress(address);
        KGXRequest.editdevicecollectinfo(this,deviceCollectBean, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.updating));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.operation_success);
                itemSmartControllerId.setRightText(deviceCollectBean.getProtocolAddress());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void deleteController(){
        KGXRequest.deletedevicecollect(this, deviceCollectBean, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.deleting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.delete_success);
                Intent intent = new Intent(getContext(), ControllerTLPKGXActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // 清除栈顶的Activity
                startActivity(intent);

//                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }
}